package com.fingard.dsp.bank.directbank.crbc01;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by Fish on 2018-12-04.
 */
public class CRBC01Transaction extends CRBC01Base implements ITransaction {

    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();
        String tmpRespCode = "";
        String tmpRespInfo = "";
        try {
            //region 一：参数定义
            Calendar qryFromCldar = Calendar.getInstance();        //记录整个查询开始日期的日历
            Calendar qryToCldar = Calendar.getInstance();          //记录整个查询截止日期的日历
            Calendar curQryFrom = Calendar.getInstance();          //本次分月查询开始日期（日历）
            Calendar curQryTo = Calendar.getInstance();            //本次分月查询结算日期（日历）
            //endregion

            //region 二：参数值初始化
            qryFromCldar.setTime(p_req7516.getDateFrom());      //设置整个查询开始日期
            qryToCldar.setTime(p_req7516.getDateTo());          //设置整个查询截止日期
            curQryFrom.setTime(qryFromCldar.getTime());         //设置本次查询开始日期
            //endregion

            //region 三：按自然月，分月（页）查询
            while (curQryFrom.compareTo(qryToCldar) <= 0 && tmpRespCode.length() == 0) {

                //region【1】计算本次查询截止日期
                if (DateHelper.compareMonth(curQryFrom, qryToCldar) == -1) {
                    //开始日期 与 截止日期 为 跨月关系时，查本月信息
                    curQryTo.setTime(curQryFrom.getTime());
                    curQryTo.set(Calendar.DAY_OF_MONTH, curQryTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    //开始日期 与 截止日期 为 同月关系时，查全部信息
                    curQryTo.setTime(qryToCldar.getTime());
                }
                //endregion

                //region【2】组装查询报文
                XmlTextWriter xmlWriter = new XmlTextWriter();
                CRBC01Header bankHeader = new CRBC01Header();
                bankHeader.tranCode = "400009";
                bankHeader.tranTime = new Date();
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("BODY");
                xmlWriter.writeElementString("ACC_NO", p_req7516.actNum);
                xmlWriter.writeElementString("CCY", convertCurToBank(p_req7516.actCur));
                xmlWriter.writeElementString("FROM_DATE", Format.Date8Format.format(curQryFrom.getTime()));
                xmlWriter.writeElementString("TO_DATE", Format.Date8Format.format(curQryTo.getTime()));
                xmlWriter.writeEndElement();//body
                xmlWriter.writeEndElement();//CRBANK
                xmlWriter.writeEndDocument();
                //endregion

                //region【3】发送请求报文
                String[] retStrArr = sendToBank(xmlWriter.toXmlString());
                //endregion

                //region【4】解析响应报文
                Map<String, String> parseResultMap = parseRespMsg(retStrArr, retAts);
                tmpRespCode = parseResultMap.get("tmpRespCode");
                tmpRespInfo = parseResultMap.get("tmpRespInfo");
                //endregion

                //region 【5】增加月数，继续查询
                curQryFrom.setTime(curQryTo.getTime());
                curQryFrom.add(Calendar.DAY_OF_MONTH, 1);
                //endregion
            }
            //endregion
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();
            retAts.writeRespInfo(tmpRespInfo);
            retAts.writeRespCode(tmpRespCode);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        return null;
    }

    //解析响应报文
    private Map<String, String> parseRespMsg(String[] retStrArr, RetAtsTrans retAts) throws Exception {
        Map<String, String> resultMap = new HashMap();
        String tmpRespCode = "";
        String tmpRespInfo = "";
        if (retStrArr[0].length() == 0) {
            StringBuilder curSbMsg = new StringBuilder();
            XmlTextReader curBkReader = loadBankRespXmlReader(retStrArr[1], curSbMsg);
            if (curBkReader != null) {
                String curRetCode = curBkReader.getFirstText("/CRBANK/HEAD/RET_CODE");
                String curRetInfo = curBkReader.getFirstText("/CRBANK/HEAD/RET_MSG");
                if ("000000".equals(curRetCode)) {
                    while (curBkReader.read("/CRBANK/BODY/ARRAY/STRUCT")) {
                        RetAtsTransDetail detail = new RetAtsTransDetail();
                        detail.reqBatchNO = curBkReader.readedXElement.getSingleText("BATCH_NO");
                        detail.recAccNum = curBkReader.readedXElement.getSingleText("ACCT_NO");
                        detail.cur = curBkReader.readedXElement.getSingleText("CCY");
                        detail.tranAmt = curBkReader.readedXElement.getSingleText("TRAN_AMT");
                        //20180704 092622
                        Date date =Format.DateTime14Format.parse(curBkReader.readedXElement.getSingleText("TRAN_TIME"));
                        detail.tranDate = Format.Date10Format.format(date);
                        detail.valueDate = detail.tranDate;
                        detail.tranTime = Format.DateTimeFormat.format(date);
                        detail.abstr = curBkReader.readedXElement.getSingleText("TRAN_NOTE");
                        detail.receiptNo = curBkReader.readedXElement.getSingleText("CHANNEL_SEQ_NO");
                        detail.bnkSeqNo = curBkReader.readedXElement.getSingleText("CHANNEL_SEQ_NO");
                        //                        TOTAL_COUNT
                        //                        SUCCESS_COUNT
                        retAts.writeRetDetail(detail);
                    }
                }else{
                    tmpRespCode = "-1";
                    tmpRespInfo = curRetInfo;
                }
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = curSbMsg.toString();
            }
        } else {
            tmpRespCode = "-1";
            tmpRespInfo = retStrArr[1];
        }
        resultMap.put("tmpRespCode", tmpRespCode);
        resultMap.put("tmpRespInfo", tmpRespInfo);
        return resultMap;
    }
}
